package com.bw.zhanggm.file.controller;


import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.zhanggm.file.config.AjaxResult;
import com.bw.zhanggm.file.config.SecurityUtil;
import com.bw.zhanggm.file.entity.HtContract;
import com.bw.zhanggm.file.openfegin.UserFeignClient;
import com.bw.zhanggm.file.service.IHtContractService;
import com.bw.zhanggm.file.vo.ContractVo;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/hetong/activiti")
public class ActivitiController {

    //发布流程使用
    @Autowired
    private RepositoryService repositoryService;

    //启动流程使用
    @Autowired
    private RuntimeService runtimeService;

    //查询任务使用
    @Autowired
    private TaskService taskService;

    //查询历史流程使用
    @Autowired
    private HistoryService historyService;


    @Autowired
    private IHtContractService contractService;


    @Autowired
    private UserFeignClient userFeignClient;


    @Autowired
    HttpServletRequest request;

    @Autowired
    SecurityUtil securityUtil;


    public void test() {
//        repositoryService.
//        historyService.createHistoricActivityInstanceQuery().
//        repositoryService.createDeploymentQuery().orderBy()
    }


    /**
     * 发布流程
     * 根据xml定义的流程，同步到activiti数据库
     * @return
     */
    /*@GetMapping("deploy")
    public AjaxResult deploy() {
        Deployment deploy = repositoryService.createDeployment()
                .name("合同审核")
                .key("hetong")
                .addClasspathResource("processes/hetong.bpmn20.xml")
                .addClasspathResource("processes/hetong.bpmn20.png")
                .deploy();
        if (log.isDebugEnabled()) {
            log.info("流程部署成功");
        }
        return AjaxResult.success();
    }*/

    /**
     * 提交审核
     * 需要流程发布的Id、业务Id（）
     * @param contract
     * @return
     */
    @PostMapping("submit")
    public AjaxResult submit(@RequestBody HtContract contract) {
        //配置流程变了
        Map<String, Object> map = new HashMap<>();
        map.put("total", contract.getTotal());
        map.put("dept", "zhangsan");
        map.put("caiwu", "lisi");
        //提交审核
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("hetong", contract.getId() + "", map);
        return AjaxResult.success();
    }

    /**
     * 我的代办
     * 根据用户Id，查询我的代办任务
     * @param contractVo
     * @return
     */
    @GetMapping("mytask")
    public AjaxResult mytask(ContractVo contractVo) {
        //获取当前登录的用户信息，可以用可以你们之前的工具类
        String token = request.getHeader("token");
        Object username = JWTUtil.parseToken(token).getPayload("username");
        //根据角色查询我的代办任务
        List<Task> list = taskService.createTaskQuery().processDefinitionKey("hetong").taskAssignee(username+"").list();
        //封装返回结果
        List<HtContract> resultList = new ArrayList<>();
        list.forEach(task->{
            //查询合同信息
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            String contractId = historicProcessInstance.getBusinessKey();
            HtContract htContract = contractService.getById(Integer.valueOf(contractId));
            //设置任务相关属性
            htContract.setTaskId(task.getId());
            htContract.setAssignee(task.getAssignee());
            htContract.setTaskName(task.getName());
            resultList.add(htContract);
        });

        return AjaxResult.success(resultList);
    }


    /**
     * 审核接口
     *
     * @return
     */
    @PostMapping("check")
    public AjaxResult check(@RequestBody HtContract htContract) {
//        Map<String, Object> vars = new HashMap<>();
        taskService.complete(htContract.getTaskId());
        return AjaxResult.success();
    }



}
